// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  console.log('main 收到登录请求参数:', event)
  
  
  switch(event.type) {
    case 'login': 
      return login(event)
  }
}

// 登录
async function login(event) {
  console.log('收到登录请求参数:', event)

  const wxContext = cloud.getWXContext()
  const openId = wxContext.OPENID

  const isUser = await checkUser(openId)

  // 如果用户存在，直接将用户信息返回前端
  if(isUser) {
    return {
      errCode: '200',
      errMsg: 'ok',
      user: {
        nickName: isUser.user_name,
        userId: isUser._id,
        avatarUrl: isUser.avatar
      }
    }
  }

  // 不存在，则将当前用户信息存进数据库
  const insertResult = await db.collection('tiezi_user')
  .add({
    data: {
        user_name: event.nickName,
        email: '',
        age: 0,
        sex: 1, // 1-男，2-女
        tel: '',
        avatar: event.avatarUrl,
        openid: openId,
        create_at:  db.serverDate()
      }
  })

  console.log('用户数据插入成功：', insertResult)

  return {
    errCode: '200',
    errMsg: 'ok',
    user: {
      nickName: event.nickName,
      userId: insertResult._id,
      avatarUrl: event.avatarUrl
    }
  }
}

// 判断用户是否存在
async function checkUser(openId) {
  const result = await db.collection('tiezi_user').where({
    openid: openId
  })
  .get()
  console.log('验证用户是否存在结果：', result.data)
  return (result.data.length ? result.data[0] : false)
}